﻿// //------------------------------------------------------------------------------
// // <copyright file="" company="Dascoba Development">
// //  Copyright © Dascoba Development 2010
// // </copyright>
// //------------------------------------------------------------------------------
namespace Dascoba.Umb.FileManager.Support
{
    using Dascoba.Umb.FileManager.Config;

    using umbraco;
    using umbraco.DataLayer;
    using umbraco.DataLayer.SqlHelpers.SqlServer;

    /// <summary>
    ///   Data Helper
    /// </summary>
    public class DataHelper
    {
        /// <summary>
        ///   Gets a value indicating whether this instance is vista db.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is vista db; otherwise, <c>false</c>.
        /// </value>
        private static bool IsVistaDb
        {
            get
            {
                return GlobalSettings.DbDSN.Contains("VistaDB");
            }
        }

        /// <summary>
        ///   The root table.
        /// </summary>
        private const string RootTable = "umbracoUserFileRoot";

        /// <summary>
        ///   Gets the database helper.  Either Sql or VistaDB
        /// </summary>
        /// <value>The database helper.</value>
        internal static ISqlHelper DatabaseHelper
        {
            get
            {
                if (IsVistaDb)
                {
                    return null;
                }

                ISqlHelper dbHelper = new SqlServerHelper(GlobalSettings.DbDSN);

                return dbHelper;
            }
        }

        /// <summary>
        ///   Assures the 'umbracoUserFileRoot' exists.
        /// </summary>
        internal static bool AssureTableExists()
        {
            if (IsVistaDb)
            {
                return false;
            }

            var dbHelper = DatabaseHelper;
            if (dbHelper == null)
            {
                return false;
            }

            var tableUtil = dbHelper.Utility.CreateTableUtility();

            if (tableUtil.ContainsTable(RootTable))
            {
                return true;
            }

            var rootTable = tableUtil.CreateTable(RootTable);

            rootTable.AddField(rootTable.CreateField("id", typeof(int)));
            rootTable.AddField(rootTable.CreateField("root", typeof(string), 255));

            dbHelper.Utility.CreateTableUtility().SaveTable(rootTable);

            return true;
        }

        /// <summary>
        ///   Assures the root record exists.
        /// </summary>
        /// <param name = "id">The id.</param>
        internal static bool AssureRootRecordExists(int id)
        {
            if (IsVistaDb)
            {
                return false;
            }

            AssureTableExists();

            var dbHelper = DatabaseHelper;
            if (dbHelper == null)
            {
                return false;
            }

            var reader = dbHelper.ExecuteReader(string.Format("select id from {0} where id={1}", RootTable, id));

            var count = 0;
            while (reader.Read())
            {
                count++;
            }

            if (count > 0)
            {
                // A record exists
                return true;
            }

            // Create root record for user
            var sql = string.Format(
                "insert into {0} values({1}, '{2}');", RootTable, id, FileManagerConfig.DefaultRootUrl);
            dbHelper.ExecuteNonQuery(sql);

            return true;
        }

        /// <summary>
        ///   Saves the root record.
        /// </summary>
        /// <param name = "id">The id.</param>
        /// <param name = "root">The root.</param>
        internal static bool SaveRootRecord(int id, string root)
        {
            if (IsVistaDb)
            {
                return false;
            }

            AssureRootRecordExists(id);
            var sqlHelper = DataLayerHelper.CreateSqlHelper(GlobalSettings.DbDSN);
            var sql = string.Format("update {0} set root='{1}' where id={2};", RootTable, root, id);
            sqlHelper.ExecuteNonQuery(sql);

            return true;
        }

        /// <summary>
        ///   Gets the file root.
        /// </summary>
        /// <param name = "userId">The user id.</param>
        /// <returns>The get file root.</returns>
        internal static string GetUserRoot(int userId)
        {
            if (IsVistaDb)
            {
                return "/";
            }

            var sqlHelper = DatabaseHelper;
            var sql = string.Format("select root from {0} where id = {1}", RootTable, userId);
            return sqlHelper.ExecuteScalar<string>(sql);
        }
    }
}